package com.gf.common.util;

import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.StringUtils;

/**
 * 邮件发送
 * 
 * @author zhuguifeng
 * 
 */
public class MailHelper {

	private static Log logger = LogFactory.getLog(MailHelper.class);
	private final static String FROM_ADDRESS = "baibai136@163.com";
	private static final JavaMailSender MAILSENDER = SpringUtils
			.getBean("mailSender");

	/**
	 * 邮件发送:单纯文本
	 * 
	 * @param toAddress
	 * @param title
	 * @param content
	 */
	public static void sendSimpleMail(String toAddress, String title,
			String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(FROM_ADDRESS);
		message.setTo(toAddress);
		if (!StringUtils.hasLength(title)) {
			title = "无主题";
		}
		message.setSubject(title);
		message.setText(content);
		message.setSentDate(new Date());

		MAILSENDER.send(message);

		logger.debug("邮件:" + toAddress + " 发送成功!");
	}

	/**
	 * 邮件发送:html格式的文本
	 * 
	 * @param toAddress
	 * @param title
	 * @param content
	 * @throws MessagingException
	 */
	public static void sendHtmlMail(String toAddress, String title,
			String content) throws MessagingException {
		MimeMessage mimeMessage = MAILSENDER.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
		helper.setFrom(FROM_ADDRESS);
		helper.setTo(toAddress);
		if (!StringUtils.hasLength(title)) {
			title = "无主题";
		}
		helper.setSubject(title);
		helper.setText(content, true);
		helper.setSentDate(new Date());
		MAILSENDER.send(mimeMessage);
	}

}
